package org.jeecg.modules.controller.register;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.modules.dic.service.IDicBeGoodAtService;
import org.jeecg.common.modules.doctor.entity.Doctor;
import org.jeecg.common.modules.doctor.entity.DoctorRegister;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterHospital;
import org.jeecg.common.modules.doctor.entity.DoctorRegisterRecord;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterHospitalService;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterRecordService;
import org.jeecg.common.modules.doctor.service.IDoctorRegisterService;
import org.jeecg.common.modules.doctor.service.IDoctorService;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterKeyVo;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterPartVo;
import org.jeecg.common.modules.doctor.vo.DoctorRegisterRecordListVo;
import org.jeecg.common.modules.doctor.vo.DoctorWholeVo;
import org.jeecg.common.modules.makeAppointment.entity.MakeAppointment;
import org.jeecg.common.modules.makeAppointment.service.IMakeAppointmentService;
import org.jeecg.common.modules.order.entity.PayOrder;
import org.jeecg.common.modules.order.service.IPayOrderService;
import org.jeecg.common.modules.patient.service.IPatientService;
import org.jeecg.common.modules.patientMedicalRecords.entity.PatientMedicalRecords;
import org.jeecg.common.modules.patientMedicalRecords.service.IPatientMedicalRecordsService;
import org.jeecg.common.modules.register.entity.RegisterPatient;
import org.jeecg.common.modules.register.entity.RegisterPayOrder;
import org.jeecg.common.modules.register.service.IRegisterPatientService;
import org.jeecg.common.modules.register.service.IRegisterPayOrderService;
import org.jeecg.common.modules.wx.entity.WxAccount;
import org.jeecg.common.modules.wx.entity.WxUserinfo;
import org.jeecg.common.modules.wx.service.IWxAccountService;
import org.jeecg.common.modules.wx.service.IWxUserinfoService;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.GetUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.enums.OrderTypeEnum;
import org.jeecg.common.util.enums.RegisterEnum;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.modules.controller.BaseController;
import org.jeecg.modules.data.Common;
import org.jeecg.modules.service.ApiOrderService;
import org.jeecg.modules.service.DateService;
import org.jeecg.modules.service.RegisterService;
import org.jeecg.modules.vo.request.PrePayOrderRequestVo;
import org.jeecg.modules.vo.respone.DoctorRegisterPartResVo;
import org.jeecg.modules.vo.respone.DoctorRegisterRecordListResVo;
import org.jeecg.modules.vo.respone.PrePayOrderResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("api/v1/register")
public class RegisterController extends BaseController {
    @Resource
    private IDoctorService doctorService;
    @Resource
    private IDicBeGoodAtService dicBeGoodAtService;
    @Resource
    private IDoctorRegisterService doctorRegisterService;
    @Resource
    private IDoctorRegisterRecordService doctorRegisterRecordService;
    @Resource
    private IDoctorRegisterHospitalService doctorRegisterHospitalService;
    @Resource
    private IWxUserinfoService wxUserinfoService;
    @Resource
    private IPatientService patientService;
    @Resource
    private ApiOrderService apiOrderService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IRegisterPatientService registerPatientService;
    @Resource
    private IRegisterPayOrderService registerPayOrderService;
    @Resource
    private IPayOrderService payOrderService;
    @Resource
    private IMakeAppointmentService makeAppointmentService;
    @Resource
    private IPatientMedicalRecordsService patientMedicalRecordsService;
    @Resource
    private IWxAccountService wxAccountService;
    @Resource
    private WeixinTemplate weixinTemplate;
    /**
     * 重新授权
     * @param
     * @return
     */
    @GetMapping("/getOpenId")
    public Result<?> getOpenId(HttpServletRequest req) throws ParseException {
        String code = req.getParameter("code");
        log.info("【微信网页授权】code={}", code);
        WxMpInMemoryConfigStorage wxStorage = new WxMpInMemoryConfigStorage();
        WxMpService wxMpService = new WxMpServiceImpl();
        if(CommonUtils.IS_ZS){
            //测试
            wxStorage.setAppId("wx4f53ddd052e1798c");
            wxStorage.setSecret("295ca96d858418e053b793a98a361544");
        }

        wxMpService.setWxMpConfigStorage( wxStorage);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        String openId = "";
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            openId = wxMpOAuth2AccessToken.getOpenId();
            Map<String,Object> map = new HashMap<>();
            GetUtils getUtils = new GetUtils();
            map.put("access_token",wxMpOAuth2AccessToken.getAccessToken());
            map.put("openid",wxMpOAuth2AccessToken.getOpenId());
            map.put("lang","zh_CN");
            String str = getUtils.getWithParams("https://api.weixin.qq.com/sns/userinfo",map);
            WxUserinfo wxUserinfo = new WxUserinfo();
            JSONObject jsonObject = JSON.parseObject(str);
            jsonObject.getString("nickname");
            wxUserinfo.setNickname(jsonObject.getString("nickname"));
            wxUserinfo.setSex(jsonObject.getInteger("sex"));
            wxUserinfo.setProvince(jsonObject.getString("province"));
            wxUserinfo.setCity(jsonObject.getString("city"));
            wxUserinfo.setCountry(jsonObject.getString("country"));
            wxUserinfo.setHeadimgurl(jsonObject.getString("headimgurl"));
            wxUserinfo.setUnionid(jsonObject.getString("unionid"));
            wxUserinfo.setOpenid(jsonObject.getString("openid"));
            WxUserinfo isHave = wxUserinfoService.getByOpenid(openId);
            if(isHave==null ||"".equals(isHave.getOpenid()) ){
                WxAccount wxAccount = wxAccountService.getByAppid(weixinTemplate.getWeixinConfig().getAppid());
                wxUserinfo.setWxAccountId(wxAccount.getAccountId());
                wxUserinfoService.save(wxUserinfo);
            }
            System.out.println("响应内容为:" + str);
        } catch (WxErrorException e) {
            log.info("【微信网页授权】{}", e);
        }
        log.info("【微信网页授权】openId={}", openId);
        Map data = new HashMap();
        data.put("openId",openId);
        return Result.ok(data);
    }

    /**
     * 医生挂号检测
     */
    @GetMapping("/check")
    public Result<?> check(@RequestParam(name="doctorId") String doctorId){
        //【一】获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(doctorId);
        if(Objects.isNull(doctor)){
            return Result.error("该医生不存在！");
        }

        //【三】检测该医生是否有挂号内容
        int registerCount = doctorRegisterService.checkRegister(doctorId);
        if(registerCount == 0){
            return Result.error("暂无挂号！");
        }
        return Result.ok();
    }

    /**
     * 挂号详情页
     * @param doctorId
     * @return
     */
    @GetMapping("/detail")
    public Result<?> queryPageList(@RequestParam(name="doctorId") String doctorId,
                                   HttpServletRequest req) throws ParseException {
        //token不存在，重新授权
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            String redirect = Common.operateUrl("doctor_register/"+doctorId);
            return Result.error(250,redirect);
        }
        log.info("token：{}",req.getHeader("X-Access-Token"));
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            String redirect = Common.operateUrl("doctor_register/"+doctorId);
            return Result.error(250,redirect);
        }
//        String openId = this.openId;

        //【一】获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(doctorId);
        if(Objects.isNull(doctor)){
            return Result.error("该医生不存在！");
        }

        Map register = new HashMap();
        int count = 0;
        //【二】检测该医生是否有挂号内容
        int registerCount = doctorRegisterService.checkRegister(doctorId);
        log.info("挂号数量：{}",registerCount);
        String date = "";
        if(registerCount != 0){
            //【1】获取预约信息
            String nowDate = DateService.getNowDate();  //当前时间
            //获取当前医生的所有出诊日期
            List<DoctorRegisterKeyVo> doctorRegisterKeyVos = doctorRegisterService.getVisitTime(doctorId,nowDate);
            log.info("获取到的出诊信息:{}",doctorRegisterKeyVos);
            int len = doctorRegisterKeyVos.size();
            for(int k = 0;k < len;k++){
                Map mapTwo = new HashMap();
                mapTwo.put("weekday", Common.dateToWeek(doctorRegisterKeyVos.get(k).getVisitTime()));
//                mapTwo.put("weekday", RegisterService.dateToWeek(doctorRegisterKeyVos.get(k).getVisitTime()));
                date = RegisterService.subStr(doctorRegisterKeyVos.get(k).getVisitTime(),5);
                mapTwo.put("date", date.replace("-","/"));
                //根据visitTime查询当天的出诊片段
                mapTwo.put("data",doctorRegisterService.getRegisterVisitPart(doctorRegisterKeyVos.get(k).getVisitTime()));
                register.put(k,mapTwo);
            }

            //【2】获取当前用户对应的挂号患者档案
            WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openId);
            count = registerPatientService.getRegisterPatientCount(wxUserinfo.getId());
        }

        Map data = new HashMap();
        data.put("doctor",doctor);
        data.put("register",register);
        data.put("archivesCount",count);
//        WeixinUtil.push(openId);
        return Result.ok(data);
    }
    /**
     * 挂号详情页
     * @param doctorId
     * @return
     */
    @GetMapping("/detail1")
    public Result<?> queryPageList1(@RequestParam(name="doctorId") String doctorId,
                                    HttpServletRequest req) throws ParseException {
        //token不存在，重新授权
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            String redirect = Common.operateUrl("doctors/buy/"+doctorId);
            return Result.error(250,redirect);
        }
        log.info("token：{}",req.getHeader("X-Access-Token"));
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            String redirect = Common.operateUrl("doctors/buy/"+doctorId);
            return Result.error(250,redirect);
        }
//        String openId = this.openId;
        openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId1：{}",openId);

        //【一】获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(doctorId);
        if(Objects.isNull(doctor)){
            return Result.error("该医生不存在！");
        }

        Map register = new HashMap();
        int count = 0;
        //【二】检测该医生是否有挂号内容
        int registerCount = doctorRegisterService.checkRegister(doctorId);
        log.info("挂号数量：{}",registerCount);
        String date = "";
        if(registerCount != 0){
            //【1】获取预约信息
            String nowDate = DateService.getNowDate();  //当前时间
            //获取当前医生的所有出诊日期
            List<DoctorRegisterKeyVo> doctorRegisterKeyVos = doctorRegisterService.getVisitTime(doctorId,nowDate);
            log.info("获取到的出诊信息:{}",doctorRegisterKeyVos);
            int len = doctorRegisterKeyVos.size();
            for(int k = 0;k < len;k++){
                Map mapTwo = new HashMap();
                mapTwo.put("weekday", Common.dateToWeek(doctorRegisterKeyVos.get(k).getVisitTime()));
//                mapTwo.put("weekday", RegisterService.dateToWeek(doctorRegisterKeyVos.get(k).getVisitTime()));
                date = RegisterService.subStr(doctorRegisterKeyVos.get(k).getVisitTime(),5);
                mapTwo.put("date", date.replace("-","/"));
                //根据visitTime查询当天的出诊片段
                mapTwo.put("data",doctorRegisterService.getRegisterVisitPart(doctorRegisterKeyVos.get(k).getVisitTime()));
                register.put(k,mapTwo);
            }

            //【2】获取当前用户对应的挂号患者档案
            WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openId);
            count = registerPatientService.getRegisterPatientCount(wxUserinfo.getId());
        }

        Map data = new HashMap();
        data.put("openId",openId);
        data.put("doctor",doctor);
        data.put("register",register);
        data.put("archivesCount",count);
        return Result.ok(data);
    }
    /**
     * 挂号详情页
     * @param doctorId
     * @return
     */
    @GetMapping("/detail2")
    public Result<?> queryPageList2(@RequestParam(name="doctorId") String doctorId,
                                    HttpServletRequest req) throws ParseException {
        //token不存在，重新授权
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            String redirect = Common.operateUrl("/chat/"+doctorId+"?doctorId="+doctorId);
            return Result.error(250,redirect);
        }
        log.info("token：{}",req.getHeader("X-Access-Token"));
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            String redirect = Common.operateUrl("/chat/"+doctorId+"?doctorId="+doctorId);
            return Result.error(250,redirect);
        }
//        String openId = this.openId;

        //【一】获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(doctorId);
        if(Objects.isNull(doctor)){
            return Result.error("该医生不存在！");
        }

        Map register = new HashMap();
        int count = 0;
        //【二】检测该医生是否有挂号内容
        int registerCount = doctorRegisterService.checkRegister(doctorId);
        log.info("挂号数量：{}",registerCount);
        String date = "";
        if(registerCount != 0){
            //【1】获取预约信息
            String nowDate = DateService.getNowDate();  //当前时间
            //获取当前医生的所有出诊日期
            List<DoctorRegisterKeyVo> doctorRegisterKeyVos = doctorRegisterService.getVisitTime(doctorId,nowDate);
            log.info("获取到的出诊信息:{}",doctorRegisterKeyVos);
            int len = doctorRegisterKeyVos.size();
            for(int k = 0;k < len;k++){
                Map mapTwo = new HashMap();
                mapTwo.put("weekday", Common.dateToWeek(doctorRegisterKeyVos.get(k).getVisitTime()));
//                mapTwo.put("weekday", RegisterService.dateToWeek(doctorRegisterKeyVos.get(k).getVisitTime()));
                date = RegisterService.subStr(doctorRegisterKeyVos.get(k).getVisitTime(),5);
                mapTwo.put("date", date.replace("-","/"));
                //根据visitTime查询当天的出诊片段
                mapTwo.put("data",doctorRegisterService.getRegisterVisitPart(doctorRegisterKeyVos.get(k).getVisitTime()));
                register.put(k,mapTwo);
            }

            //【2】获取当前用户对应的挂号患者档案
            WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openId);
            count = registerPatientService.getRegisterPatientCount(wxUserinfo.getId());
        }

        Map data = new HashMap();
        data.put("openId",openId);
        data.put("doctor",doctor);
        data.put("register",register);
        data.put("archivesCount",count);
        return Result.ok(data);
    }
    /**
     * 检查当前用户是否已经进行了当前医生的挂号
     */
    @GetMapping("/sureCheck")
    public Result<?> surePage(@RequestParam("doctorRegisterId") String doctorRegisterId,
                              @RequestParam("doctorId") String doctorId,
                              HttpServletRequest req){
        String url = Common.operateUrl("doctor_register/"+doctorId);
        //token不存在，重新授权
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            return Result.error(250,url);
        }
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            return Result.error(250,url);
        }

        //检测该用户是否已经进行了挂号
        DoctorRegisterRecord doctorRegisterRecordCheck = doctorRegisterRecordService.checkSure(openId,doctorRegisterId);
        if(Objects.nonNull(doctorRegisterRecordCheck)){
            return Result.error("您已挂号，并不要重复挂号");
        }
        return Result.ok();
    }

    /**
     * 挂号确认页——挂号前的所需数据
     */
    @GetMapping("/surePage")
    public Result<?> surePage(@RequestParam("doctorRegisterId") String doctorRegisterId,
                              HttpServletRequest req){
        String url = Common.operateUrl("doctor_register/sure/"+doctorRegisterId);
        //token不存在，重新授权
        if(Objects.isNull(req.getHeader("X-Access-Token"))){
            return Result.error(250,url);
        }
        String openId = (String) redisUtil.get(req.getHeader("X-Access-Token"));
        log.info("openId：{}",openId);
        if(Objects.isNull(openId)){
            return Result.error(250,url);
        }
//        String openId = this.openId;

        //【一】检测当前用户是否有挂号患者档案
        WxUserinfo wxUserinfo = wxUserinfoService.getByOpenid(openId);
        int count = registerPatientService.getRegisterPatientCount(wxUserinfo.getId());
        if(count == 0){
            return Result.error(220,"请先创建患者的档案！");
        }

        //【二】获取当前医生的信息：科室、医生名称、职位
        DoctorRegister doctorRegister = doctorRegisterService.getById(doctorRegisterId);
        Map doctorMap = new HashMap();
        Doctor doctor = doctorService.getById(doctorRegister.getDoctorId());
        doctorMap.put("name",doctor.getName());
        doctorMap.put("title",doctor.getTitle());
        doctorMap.put("department",doctor.getDepartment());
        doctorMap.put("departmentName",dicBeGoodAtService.getById(doctor.getDepartment()).getName());

        //【三】获取当前用户名下的所有患者
        List<RegisterPatient> patientList = registerPatientService.getPatientsByOpenid(wxUserinfo.getId()); //获者当前用户患者列表
        log.info("患者列表：{}",patientList);

        Map RegisterPatientList = new HashMap();
        //检查该用户是否曾成功挂号成功过
        RegisterPatient registerPatient = doctorRegisterRecordService.registerPatientCheck(openId);
        log.info("曾挂号的数据：{}",registerPatient);
        if(Objects.nonNull(registerPatient) && patientList.size() > 0){
            int mapKey = 0;
            for(int i = 0;i < patientList.size();i++){
                if(registerPatient.getId().equals(patientList.get(i).getId())){
                    RegisterPatientList.put(0,patientList.get(i));
                }else{
                    mapKey++;
                    RegisterPatientList.put(mapKey,patientList.get(i));
                }
            }
        }else if(patientList.size() > 0){
            int mapKey = 0;
            for(RegisterPatient patient :patientList){
                RegisterPatientList.put(mapKey,patient);
                mapKey++;
            }
        }
        log.info("更新后的数据：{}",RegisterPatientList);

        //【四】获取当前挂号的信息：预约医院、号种、就诊时间、号源数量、挂号费用
        DoctorRegisterPartVo doctorRegisterPartVo = doctorRegisterService.getRegisterPart(doctorRegisterId);
        DoctorRegisterPartResVo partResVo = new DoctorRegisterPartResVo();
        BeanUtils.copyProperties(doctorRegisterPartVo,partResVo);  //把前边的值赋值到后边

        DoctorRegisterRecord doctorRegisterRecord = doctorRegisterRecordService.getSureRecord(doctorRegisterId);
        partResVo.setVisitNum(doctorRegisterRecord.getVisitNum());
        partResVo.setRecordId(doctorRegisterRecord.getId());
        log.info("挂号的信息：{}",partResVo);

        Map result = new HashMap();
        result.put("doctor",doctorMap);
        result.put("patientList",RegisterPatientList);
        result.put("register",partResVo);

        return Result.ok(result);
    }

    /**
     * 挂号提交，确认支付
     * 挂号id，患者ID，患者性质，就诊序号
     */
    @PostMapping("/surePay")
    public Result<?> surePay(@RequestBody DoctorRegisterRecordVO doctorRegisterRecordVO,
                             HttpServletRequest req){
        DoctorRegisterRecord doctorRegisterRecord = new DoctorRegisterRecord();
        BeanUtils.copyProperties(doctorRegisterRecordVO, doctorRegisterRecord);
        String openId = doctorRegisterRecord.getOpenid();
        String parentId = doctorRegisterRecord.getPatientId();
        //【一】检查该患者是否预约了同一时间段的号源
        boolean registerCheck = doctorRegisterRecordService.checkRegisterSame(
                doctorRegisterRecord.getDoctorRegisterId(),openId,parentId);

        if(doctorRegisterRecordVO.getIsBegin() != null && doctorRegisterRecordVO.getIsBegin() == 1){
            //获取当前时间
            Date nowDate = new Date();  //当前时间
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm");
            SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-");
            String date = sdf4.format(nowDate)+ doctorRegisterRecordVO.getDateTime()+ CommonUtils.BEGINTIME;
            try {
                Date date1 = sdf3.parse(date);
                Date date2 = sdf3.parse(sdf4.format(nowDate)+ doctorRegisterRecordVO.getDateTime()  +" "+sdf2.format(nowDate));
                System.out.println(date1.getTime());
                System.out.println(date2.getTime());
                if(date1.getTime()-date2.getTime()>=0){
                    return Result.error("10点开启抢号，敬请期待！");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


//        if(request.getIsBegin() == 1 && sdf.format(nowDate).equals("18:00")){
//            return Result.error("10点开启抢号，敬请期待！");
//        }
        if(registerCheck){
            return Result.error("请不要重复选择同一号源！");
        }

        //【二】检测该挂号序号有误已被提前挂号
//        boolean check = doctorRegisterRecordService.checkRegister(
//                doctorRegisterRecord.getDoctorRegisterId(),Integer.valueOf(doctorRegisterRecord.getVisitNum()));
//        if(check){
//            return Result.error("当前序号已被占用，请重新选择！");
//        }

        DoctorRegisterRecord doctorRr = doctorRegisterRecordService.getById(doctorRegisterRecord.getDoctorRegisterId());
        if(doctorRr!=null && null != doctorRr.getStatus() && ("0".equals(doctorRr.getStatus()) || "3".equals(doctorRr.getStatus()) ||"4".equals(doctorRr.getStatus())||"5".equals(doctorRr.getStatus()))){
            return Result.error("当前序号已被占用，请重新选择！");
        }

        //【三】更改挂号记录状态
        doctorRegisterRecord.setVisitNum(null);
        doctorRegisterRecord.setOpenid(openId);
        doctorRegisterRecord.setDoctorRegisterId(null);
        doctorRegisterRecord.setRegisterTime(new Date());
        doctorRegisterRecordService.updateById(doctorRegisterRecord);

        //【四】微信支付接口所需参数
        PrePayOrderRequestVo prePayOrderRequestVo = new PrePayOrderRequestVo();
        DoctorRegister doctorRegister = doctorRegisterRecordService.getRegisterByRecordId(doctorRegisterRecord.getId());
        prePayOrderRequestVo.setDoctorId(doctorRegister.getDoctorId());
        prePayOrderRequestVo.setOrderType(OrderTypeEnum.REGISTER.getCode()); //挂号类型：OrderTypeEnum.REGISTER.getCode()
        prePayOrderRequestVo.setRelationId(doctorRegisterRecord.getId());
        return Result.ok(prePayOrderRequestVo);
    }
    /**
     * 视频预约提交，确认支付
     * 挂号id，患者ID，患者性质，就诊序号
     */
    @PostMapping("/sureSPPay")
    public Result<?> sureSPPay(@RequestBody DoctorRegisterRecord doctorRegisterRecord,
                               HttpServletRequest req){
        String openId = doctorRegisterRecord.getOpenid();
        String parentId = doctorRegisterRecord.getPatientId();
        //【一】检查该患者是否预约了同一时间段的号源
        boolean registerCheck = doctorRegisterRecordService.checkRegisterSame(
                doctorRegisterRecord.getDoctorRegisterId(),openId,parentId);
        if(registerCheck){
            return Result.error("请不要重复选择同一号源！");
        }

        //【二】检测该挂号序号有误已被提前挂号
//        boolean check = doctorRegisterRecordService.checkRegister(
//                doctorRegisterRecord.getDoctorRegisterId(),Integer.valueOf(doctorRegisterRecord.getVisitNum()));
//        if(check){
//            return Result.error("当前序号已被占用，请重新选择！");
//        }

        DoctorRegisterRecord doctorRr = doctorRegisterRecordService.getById(doctorRegisterRecord.getDoctorRegisterId());
        if(doctorRr!=null && null != doctorRr.getStatus() && ("0".equals(doctorRr.getStatus()) || "3".equals(doctorRr.getStatus()) ||"4".equals(doctorRr.getStatus())||"5".equals(doctorRr.getStatus()))){
            return Result.error("当前序号已被占用，请重新选择！");
        }

        //【三】更改挂号记录状态
        doctorRegisterRecord.setVisitNum(null);
        doctorRegisterRecord.setOpenid(openId);
        doctorRegisterRecord.setDoctorRegisterId(null);
        doctorRegisterRecord.setRegisterTime(new Date());
        doctorRegisterRecordService.updateById(doctorRegisterRecord);

        //【四】微信支付接口所需参数
        PrePayOrderRequestVo prePayOrderRequestVo = new PrePayOrderRequestVo();
        DoctorRegister doctorRegister = doctorRegisterRecordService.getRegisterByRecordId(doctorRegisterRecord.getId());
        prePayOrderRequestVo.setDoctorId(doctorRegister.getDoctorId());
        prePayOrderRequestVo.setOrderType(OrderTypeEnum.VIDEO.getCode()); //挂号类型：OrderTypeEnum.REGISTER.getCode()
        prePayOrderRequestVo.setRelationId(doctorRegisterRecord.getId());
        return Result.ok(prePayOrderRequestVo);
    }
    /**
     * 患者的挂号记录列表
     */
    @GetMapping("/record")
    public Result<?> record(@RequestParam String openid, String status){

//       openid = "oRBzQs-tc5pXR8oaHMYGEt2qNqYw";
        List<DoctorRegisterRecordListResVo> doctorRegisterRecordListResVoList = null;
        try {
            String nowDate = DateService.getNowDate() + " 23:59:59";  //当前日期
            String beforeThirtyDate = DateService.getFutureDate(-30) + " 00:00:00";  //获取前30天的日期字符串
            log.info("当前时间：{}",nowDate);
            log.info("一个月前时间：{}",beforeThirtyDate);
            List<DoctorRegisterRecordListVo> registerRecords = doctorRegisterRecordService.getRecordByOpenid(openid,nowDate,beforeThirtyDate,status);

            log.info("=========返回结果：{}",registerRecords);
            doctorRegisterRecordListResVoList = new ArrayList<>();
            for(DoctorRegisterRecordListVo recordListVo : registerRecords){
                DoctorRegisterRecordListResVo recordListResVo = new DoctorRegisterRecordListResVo();
                BeanUtils.copyProperties(recordListVo,recordListResVo);
                DoctorRegisterHospital doctorhospital = doctorRegisterHospitalService.getById(recordListResVo.getRegisterHospitalId());
                recordListResVo.setRegisterHospitalName(doctorhospital.getName()); //就诊医院
                recordListResVo.setAddress(doctorhospital.getAddress());
                //            recordListResVo.setVisitTime(RegisterService.subStr(recordListResVo.getVisitTime(),5)); //就诊日期
                recordListResVo.setVisitTime(recordListVo.getVisitTime() +" "+recordListVo.getStartTime().substring(0,5)+"~"+recordListVo.getEndTime().substring(0,5));
                recordListResVo.setHeadImg(recordListVo.getHeadImg());
                if(recordListVo.getRegisterNature().contains("线下")){
                    recordListResVo.setPrice(new BigDecimal(BigInteger.ZERO));
                }else{
                    recordListResVo.setPrice(recordListVo.getPrice());
                }

                //获取医生信息
                DoctorWholeVo doctor = doctorService.doctorWhole(recordListResVo.getDoctorId());
                recordListResVo.setDoctorName(doctor.getName());
                recordListResVo.setTitle(doctor.getTitle());
                recordListResVo.setDepartmentName(doctor.getDepartmentName());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                //判断是否是待支付，待支付5分钟失效，变为取消订单
                LambdaQueryWrapper<WxUserinfo> query = Wrappers.lambdaQuery();
                query.eq(WxUserinfo::getOpenid,openid);
                log.info(openid);
                WxUserinfo wxUserinfo = wxUserinfoService.getOne(query); //获取微信用户
                RegisterPayOrder payOrder = new RegisterPayOrder();
                payOrder.setDoctorId(doctor.getId());
                payOrder.setRelationId(recordListVo.getRegisterId());
//                payOrder.setStatus(RegisterEnum.OPERATE.getCode());
                recordListResVo.setRelationId(recordListVo.getRegisterId());
                recordListResVo.setOrderPayId(recordListVo.getId());
                recordListResVo.setId(recordListVo.getRegisterId());
                payOrder.setWxUserinfoId(wxUserinfo.getId());
                RegisterPayOrder registerPayOrder = registerPayOrderService.getByRelationId(payOrder);


                //获取当前时间
                Date nowDate1 = new Date();  //当前时间

                if(recordListVo.getStatus() == 2||recordListVo.getStatus()==4){
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String yesTime = recordListVo.getVisitTime() + " 18:00";
                    Date date=sdf.parse(yesTime);
                    long time =date.getTime()-60*60*24;
                    Calendar now = Calendar.getInstance();
                    now.setTime(date);
                    System.out.println(sdf.format(now.getTime()));
                    now.add(Calendar.DAY_OF_MONTH, -1);

                    String yersDay = sdf.format(now.getTime());
                    date=sdf.parse(yersDay);
                    if(nowDate1.compareTo(date)>=0){
                        recordListResVo.setIsAllowed("1");
                    }
                }
                if(registerPayOrder!=null ){
                    if(registerPayOrder.getStatus() == RegisterEnum.PAY.getCode()){
                        Date createTime = registerPayOrder.getCreateTime();
                        long shixiaoTime = (createTime.getTime()+1000*60*5);
                        recordListResVo.setSurpleTime(sdf.format(shixiaoTime));

                        recordListResVo.setPatientId(registerPayOrder.getPatientId());
                        recordListResVo.setStatus(registerPayOrder.getStatus());
                        String shixiaoStr = sdf.format(shixiaoTime);
                        Date shixiaodate=sdf.parse(shixiaoStr);
                        //判断当前时间是否已超过失效时间
                        if(shixiaodate.compareTo(nowDate1)<0 && registerPayOrder.getStatus() == 0){
                            DoctorRegisterRecord doctorRegisterRecord = new DoctorRegisterRecord();
                            doctorRegisterRecord.setId(recordListVo.getId());
                            doctorRegisterRecord.setStatus(5);
                            recordListResVo.setStatus(5);
                            doctorRegisterRecordService.updateById(doctorRegisterRecord);
                        }
                    }else {

                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                        String yesTime = recordListVo.getVisitTime() + " 18:00";
                        Date date=sdf.parse(yesTime);
                        long time =date.getTime()-60*60*24;
                        Calendar now = Calendar.getInstance();
                        now.setTime(date);
                        System.out.println(sdf.format(now.getTime()));
                        now.add(Calendar.DAY_OF_MONTH, -1);

                        String yersDay = sdf.format(now.getTime());
                        date=sdf.parse(yersDay);
                        if(nowDate1.compareTo(date)>=0){
                            recordListResVo.setIsAllowed("1");
                        }
                    }
                }else{
                    if(recordListVo.getStatus() ==5){continue;}
                    switch (recordListVo.getStatus()){
                        case 0:
                            recordListResVo.setStatus(0);
                            break;
                        case 1:
                            recordListResVo.setStatus(1);
                            break;
                        case 2:
                            recordListResVo.setStatus(2);
                            break;
                        case 3:
                            recordListResVo.setStatus(3);
                            break;
                        case 4:
                            recordListResVo.setStatus(4);
                            break;
                        case 5:
                            recordListResVo.setStatus(5);
                            break;
                        case 6:
                            recordListResVo.setStatus(6);
                            break;
                        default:
                            recordListResVo.setStatus(0);
                    }
                }
                doctorRegisterRecordListResVoList.add(recordListResVo);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return Result.ok(doctorRegisterRecordListResVoList);
    }

    /**
     * 患者的挂号记录详情
     */
    @GetMapping("/recordDetail")
    public Result<?> recordDetail(@RequestParam("recordId") String recordId,@RequestParam("orderPayId") String orderPayId){


        //获取订单状态
        RegisterPayOrder rpo = registerPayOrderService.getById(orderPayId);

        // 获取详情信息
        DoctorRegisterRecordListVo registerRecord = doctorRegisterRecordService.getRecordById(recordId);
//        DoctorRegisterRecordListVo registerRecord = doctorRegisterRecordService.getRecordById(rpo.getRelationId());
        if(Objects.isNull(registerRecord)){
            return Result.error("该记录不存在");
        }
        DoctorRegisterRecordListResVo recordListResVo = new DoctorRegisterRecordListResVo();
        BeanUtils.copyProperties(registerRecord,recordListResVo);


        //设置医院名称
        recordListResVo.setRegisterHospitalName(doctorRegisterHospitalService.getById(recordListResVo.getRegisterHospitalId()).getName()); //就诊医院
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //获取医生信息
        DoctorWholeVo doctor = doctorService.doctorWhole(recordListResVo.getDoctorId());
        recordListResVo.setDoctorName(doctor.getName());
        recordListResVo.setTitle(doctor.getTitle());
        recordListResVo.setDepartmentName(doctor.getDepartmentName());
        recordListResVo.setEndPayTime(registerRecord.getEndPayTime());
        recordListResVo.setCreateTime(registerRecord.getCreateTime());
        if(registerRecord.getRegisterNature().contains("社保")){
            recordListResVo.setPrice(new BigDecimal(BigInteger.ZERO));
        }else{
            recordListResVo.setPrice(registerRecord.getPrice());
        }
        try {
            //获取当前时间
            Date nowDate1 = new Date();  //当前时间
            Date createTime = sdf.parse(registerRecord.getCreateTime());
            long shixiaoTime = (createTime.getTime()+1000*60*5);
            String shixiaoStr = sdf.format(shixiaoTime);
            Date shixiaodate=sdf.parse(shixiaoStr);
            //判断当前时间是否已超过失效时间
            if(shixiaodate.compareTo(nowDate1)<0 && registerRecord.getStatus() == 0){
                DoctorRegisterRecord doctorRegisterRecord = new DoctorRegisterRecord();
                doctorRegisterRecord.setId(registerRecord.getId());
                doctorRegisterRecord.setStatus(5);
                recordListResVo.setStatus(5);
                doctorRegisterRecordService.updateById(doctorRegisterRecord);
            }else {
                recordListResVo.setStatus(registerRecord.getStatus());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

//        recordListResVo.setOrderPayTime(registerRecord.getEndPayTime() == null ? null : sdf.format(registerRecord.getEndPayTime()));
//        recordListResVo.setOrderTime(registerRecord.getCreateTime() == null ? null : sdf.format(registerRecord.getCreateTime()));
        recordListResVo.setVisitTime(registerRecord.getVisitTime() +" "+registerRecord.getStartTime().substring(0,5)+"~"+registerRecord.getEndTime().substring(0,5));
        return Result.ok(recordListResVo);
    }
    /**
     * 患者的挂号记录列表
     */
    @GetMapping("/recordSP")
    public Result<?> recordSP(@RequestParam String openid, String status, Integer shopType){
        List<PayOrderVO> PayOrderVOS = new ArrayList<>();
        List<PayOrder> payOrders = payOrderService.list(Wrappers.lambdaQuery(PayOrder.class).eq(PayOrder::getOpenid,openid).eq(PayOrder::getShopType,shopType).eq(PayOrder::getStatus,status));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (PayOrder payOrder: payOrders) {
            PayOrderVO vo = new PayOrderVO();
            BeanUtils.copyProperties(payOrder,vo);
            Doctor doctor = doctorService.getById(vo.getDoctorId());
            vo.setDoctorName(doctor.getName());
            vo.setAmount(payOrder.getAmount()*0.01);
            MakeAppointment make = makeAppointmentService.getById(vo.getRelationId());
            vo.setOrderTime(sdf.format(make.getDate() ) + " " + make.getStartTime() + "~"+ make.getEndTime() + make.getVartPart());
            PatientMedicalRecords patientMedicalRecord = patientMedicalRecordsService.getById(vo.getMedicalId());
            vo.setPatientName(patientMedicalRecord.getPatientName());
            PayOrderVOS.add(vo);
        }
        System.out.println(PayOrderVOS);
        return Result.ok(PayOrderVOS);
    }

}

